package org.lee.img.impl;

import org.lee.img.IRecognizeMainColor;
import org.soualid.colorthief.MMCQ;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * @author jackielee
 * @version 1.0
 * @description RecognizeMainColor
 * @date 2021/5/10
 */
public class RecognizeMainColor implements IRecognizeMainColor {
  @Override
  public String run(String path) {
    try {
      MMCQ.CMap result = MMCQ.computeMap(ImageIO.read(new File(path)), 10);
      Iterator<MMCQ.DenormalizedVBox> boxes = result.getBoxes().iterator();
      StringBuilder sb = new StringBuilder(256);
      while (boxes.hasNext()) {
        MMCQ.DenormalizedVBox denormalizedVBox = (MMCQ.DenormalizedVBox) boxes.next();
        int[] color = denormalizedVBox.getColor();
        sb.append(String.format("rgb(%d,%d,%d);", color[0], color[1], color[2]));
      }
      return sb.toString();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  //  public int getMainColor(Bitmap bitmap) {
  //    long start = System.currentTimeMillis();
  //    int r = 0;
  //    if (bitmap == null) {
  //      return r;
  //    }
  //    int width = bitmap.getWidth();
  //    int height = bitmap.getHeight();
  //    Log.i("okunu", "width = " + width + " height = " + height);
  //    int[] pixels = new int[width * height];
  //    int totalR = 0, totalG = 0, totalB = 0;
  //    int sampleColor = 0;
  //    int sampleCount = 0;
  //    int red = 0, green = 0, blue = 0;
  //    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
  //    Log.i("okunu", "pixels.length = " + pixels.length);
  //    for (int i = 0; i < height; i += 4) {
  //      int s = i * width;
  //      for (int j = 0; j < width; j += 4) {
  //        sampleColor = pixels[s + j];
  //        red = Color.red(sampleColor);
  //        green = Color.green(sampleColor);
  //        blue = Color.blue(sampleColor);
  //        totalR += red;
  //        totalG += green;
  //        totalB += blue;
  //        sampleCount++;
  //      }
  //    }
  //    Log.i("okunu", "sampleCount = " + sampleCount);
  //    totalR = (int) Math.floor(totalR / sampleCount);
  //    totalG = (int) Math.floor(totalG / sampleCount);
  //    totalB = (int) Math.floor(totalB / sampleCount);
  //    r = Color.rgb(totalR, totalG, totalB);
  //    Log.i("okunu", "time = " + (System.currentTimeMillis() - start));
  //    return r;
  //  }
}
